#!/bin/bash

# 获取当前目录
current_dir=$(pwd)

# 构建编译结果目录或清理已有目录
build_dir="$current_dir/build"

if [ ! -d "$build_dir" ]; then
    echo "Creating build directory..."
    mkdir -p "$build_dir"
else
    echo "--------------------------------- Cleaning ---------------------------------"
    # 清除 build 目录中的所有 .exe 文件
    if [ -n "$(find "$build_dir" -maxdepth 1 -name '*' -print -quit)" ]; then
        rm -f "$build_dir"/*
        echo "Cleaning EXE."
    fi
    echo "----------------------------------------------------------------------------"
    echo "Cleaning completed."
    echo
fi

# 判断 cjdoc 是否已经编译
cjdoc_binary_en="$current_dir/target/release/bin/cjdoc_en"
cjdoc_binary_zh_cn="$current_dir/target/release/bin/cjdoc_zh-cn"

if [ -f "$cjdoc_binary_en" ] && [ -f "$cjdoc_binary_zh_cn" ]; then
    echo "cjdoc has been compiled."

    # 提示用户输入逻辑值 (循环直到输入有效)
    while true; do
        read -p "Do you want to recompile? (Y/N): " choiceRC
        # 转换为小写并检查
        case "${choiceRC,,}" in
            y|yes)
                recompile=true
                break
                ;;
            n|no)
                echo "Skip compilation cjdoc."
                recompile=false
                break
                ;;
            *)
                echo "Invalid value. Please enter Y or N."
                ;;
        esac
    done
else
    # 如果二进制文件不存在，必须重新编译
    recompile=true
fi

# 如果需要重新编译，则执行编译和拷贝
if [ "${recompile:-false}" = true ]; then
    echo "----------------------------- Compiling cjdoc -------------------------------"
    cjpm update
    cjpm build --cfg_en -o cjdoc_en
    cjpm build --cfg_zh_cn -o cjdoc_zh-cn
    echo "----------------------------------------------------------------------------"
    echo "cjdoc compilation completed."
    echo

    echo "------------------------------- Copy Result -------------------------------"
    # 拷贝编译结果到 build 目录
    target_dir="$current_dir/target/release/bin"
    if [ -d "$target_dir" ]; then
        cd "$target_dir" || exit 1
        for file in [!.]*; do
            if [[ "$file" != *.* ]] && [ -f "$file" ]; then
                echo "Copy $file to $build_dir"
                cp "$file" "$build_dir"/
            fi
        done
    else
        echo "Error: Target directory $target_dir does not exist."
        exit 1
    fi
    echo "---------------------------------------------------------------------------"
    echo
fi

echo "completed..."
# 注意：Linux 下没有 'pause'，通常脚本执行完就退出。
# 如果你想暂停，可以使用：
# read -p "Press Enter to continue..." </dev/tty